import re
from Baidu_Text_transAPI import translate
from work_zykj.mysql import mysql_util as sql_util
import json

# java文件按照云上农牧规则国际化

"""处理中文"""

# 百度翻译（免费）https://api.fanyi.baidu.com/product/113

# 百度认证信息
# APP ID：20250715002407008
# 密钥：xD5jLaqbGESuy00oWo28

"""将中文翻译成各种语言存储到数据库,无则insert，有则忽略
如果中文翻译存在，则返回key，否则插入数据库"""


def handle_database(key, item, to_lang):
    sql = "SELECT * FROM pc_i18n a where a.label_zh = '{}' limit 1".format(item)
    rs = sql_util.select_by_sql(sql)
    rs = json.loads(rs)
    field_lang = to_lang
    if to_lang == 'vie':
        field_lang = 'vi'

    if len(rs) > 0:
        data = rs[0]
        key = data['code']
        # 如果该语言没有翻译则更新翻译
        label = data['label_' + field_lang]
        if label == 'None':
            if 'zh' != to_lang:
                label = translate('zh', to_lang, item)

                sql = "update pc_i18n set label_{} = '{}' where code = '{}'".format(field_lang, label, key)
                print(sql)
                sql_util.execute(sql)
                print(sql)
    else:
        # 如果to_lang不是中文则翻译
        # 默认是中文
        label = item
        if 'zh' != to_lang:
            label = translate('zh', to_lang, item)
        # 插入翻译
        sql = "insert into pc_i18n (code,label_{},create_time,create_user,update_time) values ('{}','{}',now(),'yjz',now())".format(
            field_lang, key, label)
        sql_util.execute(sql)
        print(sql)
    return key


# item 中文项
def handle_chinese(line, item):
    # 将中文转成key（翻译成英语，把空格替换成"."）
    en = translate('zh', 'en', item)
    # print(en)
    # 将中文翻译成各种语言，key作为主键存储到数据库
    key = en.replace(' ', '.')
    # "]It.doesn't.exist"
    key = key.replace("\'", '')

    # 将中文翻译成各种语言存储到数据库
    key = handle_database(key, item, 'zh')
    key = handle_database(key, item, 'en')
    key = handle_database(key, item, 'th')
    key = handle_database(key, item, 'vie')
    print('-- ' + key + ' - ' + item)
    # 将文件中的中文替换为lang("key")
    line_new = line.replace('"' + item + '"', 'lang("' + key + '")')

    return line_new


"""抓取双引号之间的中文，翻译，转换为英文key，回写文件"""


def get_ignore_flag(line: str):
    if 'log.' in line:
        return True
    if 'lang(' in line:
        return True


def extract_quoted_chinese(file_path):
    # 匹配双引号内的内容，并筛选出含中文的部分
    pattern = re.compile(r'"([^"\\]*(\\.[^"\\]*)*)"')
    s = ''
    # chinese_set = set()
    # 读取全部的中文
    lines = []
    data = 'import static cloudpc.lib.i18n.MessageHelper.lang;\n'
    import_flag = True
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        for index, line in enumerate(lines):
            if data in line:
                import_flag = False
            # 忽略log日志
            if get_ignore_flag(line):
                continue

            # 替换 %s -> "+"%s"+"
            lines[index] = line.replace('%s', '"+"%s"+"')
            # print(line, end='')
            for match in pattern.findall(lines[index]):
                for item in match:
                    # print(item, end='\n')
                    if is_chinese(item):
                        # print(item)
                        # chinese_set.add(item)
                        # 处理中文
                        lines[index] = handle_chinese(lines[index], item)
    # 插入的数据
    if import_flag:
        lines.insert(3, data)
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)

    return s


"""正则表达式判断字符串是否为中文"""


def is_chinese(s):
    return bool(re.search('[\u4e00-\u9fa5]', s))


if __name__ == '__main__':
    # 读取文件
    file_path = 'C:/Users/asyf/Desktop/' + 'SaleSimpleServiceImpl.java'
    s = extract_quoted_chinese(file_path)
    print(type(s))
    # print(is_chinese('领药单药品已完成出库，请及时录入免疫'))
